package cn.zorbus.logback;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.pattern.DynamicConverter;
import org.apache.commons.collections4.map.HashedMap;
import org.jetbrains.annotations.NotNull;

import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * create in 2024/8/2 11:53
 *
 * @author shishaodong
 * @version 0.0.1
 */
@SuppressWarnings("unused")
public class SensitiveDataConverter extends DynamicConverter<ILoggingEvent> {

    private static final Map<String, String> SENSITIVE_DATA_MAP = new HashedMap<>();

    static {
        SENSITIVE_DATA_MAP.put("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        SENSITIVE_DATA_MAP.put("(\\w{2})\\w{2,}(\\w?@\\w+)", "$1****$2");
        SENSITIVE_DATA_MAP.put("(\\d{4})\\d{10}(\\d{4})", "$1**********$2");
    }

    @Override
    public String convert(@NotNull ILoggingEvent event) {
        var messageRef = new AtomicReference<>(event.getFormattedMessage());
        SENSITIVE_DATA_MAP.forEach((key, value) -> messageRef.set(messageRef.get().replaceAll(key, value)));
        return messageRef.get();
    }
}
